package com.yc.fav.web;

import com.yc.fav.Utils;
import com.yc.fav.entity.Fav;
import com.yc.fav.entity.User;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IFavService;
import com.yc.fav.vo.Result;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/6
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/addFav")
public class AddFavServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = new Result();

        if(req.getSession().getAttribute("loginedUser")==null){
            result.setCode(0);
            result.setMsg("请先登录系统");
            Utils.print(resp,result);
            return;
        }
        User user = (User) req.getSession().getAttribute("loginedUser");

        // TODO 完成登录功能之后, 请回复这里的代码
       /* User user = new User();
        user.setId(1);*/

        String name = req.getParameter("name");
        String addr = req.getParameter("addr");
        String tags = req.getParameter("tags");
        String intro = req.getParameter("intro");
        String image = req.getParameter("image");
        String id = req.getParameter("id");

        Fav fav = new Fav();
        fav.setUid(user.getId());
        fav.setName(name);
        fav.setIntro(intro);
        fav.setAddr(addr);
        fav.setTags(tags);
        fav.setImage(image);

        if(id!=null){
            fav.setId(Integer.parseInt(id));
        }

        ApplicationContext cxt = (ApplicationContext) getServletContext().getAttribute("cxt");
        IFavService biz = cxt.getBean(IFavService.class);
        try {
            if(fav.getId()!=null){
                biz.modify(fav);
            } else {
                biz.add(fav);
            }
            result.setCode(1);
            result.setMsg("添加链接成功!");
        } catch (BizException e) {
            result.setCode(-1);
            result.setMsg(e.getMessage());
        } catch (RuntimeException e){
            e.printStackTrace();
            result.setCode(-2);
            result.setMsg("系统繁忙,稍后再试");
        }

        Utils.print(resp,result);

    }
}
